package pl.ivmx.cinema;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

public class ActorDao extends BaseDao {

	private static ActorDao instance = null;
	private List<ActorObserver> observers ;

	private List<BasicEntity> notifications;
	private ThreadManager threadManager;
	private DaoThread daoThread;
	private EntityManager em;
	
	private ActorDao() {
		threadManager = ThreadManager.getInstance();
		notifications = new ArrayList<BasicEntity>();
		observers = new ArrayList<ActorObserver>();
		
		EntityManagerFactory emf = 
			Persistence.createEntityManagerFactory("cinemaJPA");
		em = emf.createEntityManager();
	}

	public static ActorDao getInstance() {
		if (instance == null) {
			instance = new ActorDao();
		}
		return instance;
	}

	@Override
	public void findNotifications() {
		ResultSet newActors = JDBCConnection.getInstance().executeQuery(
				"Select * from LogActor");
		String actorID;
		try {
			while (newActors.next()) {
				String logID = newActors.getString("id");
				actorID = newActors.getString("actor_id");
				System.out.println("Nowy idek: "+actorID);
				
				ResultSet actors = JDBCConnection.getInstance().executeQuery(
						"Select * from actor where id=" + actorID);
						
					try {
						while (actors.next()) {

						String bio = actors.getString("bio");
						Integer id = Integer.parseInt(actors.getString("id"));
						String photoURL = actors.getString("photoURL");
						String name = actors.getString("name");

						ActorEntity actor = new ActorEntity(id, name, photoURL, bio);

						notifications.add(actor);

						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
					JDBCConnection.getInstance().executeStatement("delete from LogActor where id = " + logID);
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void addListener(IObserver io) {
		if (io instanceof ActorObserver) {
			observers.add((ActorObserver) io);
			
		}
		
		if (observers.size() == 1 ){
			if (daoThread == null) {
				daoThread = (DaoThread) ThreadManager.getInstance().createThread(this);
				
			}
			ThreadManager.getInstance().start(daoThread);
		} 
		
	}

	@Override
	public void notifyListener() {
		for (BasicEntity be : notifications) {
			for (ActorObserver o : observers) {
				o.update(be);
			}
		}
		notifications.clear();
	}

	@Override
	public void removeListener(IObserver io) {
		if (io instanceof ActorObserver) {
			observers.remove((ActorObserver) io);
		}
		
		if (observers.size() == 0){
			if (daoThread != null){
				ThreadManager.getInstance().stopThread(daoThread);
			}
		}
	}

}
